package com.howie.parnote.jms;

import com.howie.parnote.module.SharerModule;
import com.howie.parnote.util.LogUtil;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.log4j.Logger;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

/**
 * <p>Title: parnote</p>
 * <p>
 * Description: parnote
 * </p>
 *
 * @author huangyan
 *         Created by HY on 2015/4/17 0017.
 * @version v1.0.0
 */
public class UserMessageConverter implements MessageConverter {

	private static Logger logger = LogUtil.getLogger(UserMessageConverter.class);

	/**
	 * 将Java对象转换为Message
	 *
	 * @param obj
	 * @param session
	 * @return
	 * @throws JMSException
	 * @throws MessageConversionException
	 */
	@Override
	public Message toMessage(Object obj, Session session) throws JMSException, MessageConversionException {
		if (logger.isDebugEnabled()) {
			logger.debug("Convert User object to JMS message: " + obj);
		}

		if (obj instanceof SharerModule) {
			ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage();
			msg.setObject((SharerModule) obj);
			return msg;
		} else {
			logger.error("Object:[" + obj + "] is not a instance of SharerModule.");
			throw new JMSException("Object:[" + obj + "] is not a instance of SharerModule.");
		}
	}

	/**
	 * 将Message转换为Java对象
	 *
	 * @param message
	 * @return
	 * @throws JMSException
	 * @throws MessageConversionException
	 */
	@Override
	public Object fromMessage(Message message) throws JMSException, MessageConversionException {

		if (logger.isDebugEnabled()) {
			logger.debug("Receive JMS message: " + message);
		}

		if (message instanceof ObjectMessage) {
			ObjectMessage oMsg = (ObjectMessage) message;

			if (oMsg instanceof ActiveMQObjectMessage) {
				ActiveMQObjectMessage aMsg = (ActiveMQObjectMessage) oMsg;

				try {
					SharerModule sharerModule = (SharerModule) aMsg.getObject();

					return sharerModule;
				} catch (Exception e) {
					logger.error("Message:[" + message + "] is not a instance of SharerModule.");
					throw new JMSException("Message:[" + message + "] is not a instance of SharerModule.");
				}
			} else {
				logger.error("Message:[" + message + "] is not "
						+ "a instance of ActiveMQObjectMessage[SharerModule].");
				throw new JMSException("Message:[" + message + "] is not "
						+ "a instance of ActiveMQObjectMessage[SharerModule].");
			}
		} else {
			logger.error("Message:[" + message + "] is not a instance of ObjectMessage.");
			throw new JMSException("Message:[" + message + "] is not a instance of ObjectMessage.");
		}
	}
}
